package com.core.family.admin.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.common.domain.response.R;
import com.core.common.manger.storage.IStorageService;
import com.core.family.admin.domain.po.PlatStorage;
import com.core.family.admin.domain.po.PlatStorageLogic;
import com.core.family.admin.service.PlatStorageLogicService;
import com.core.family.admin.service.PlatStorageService;
import lombok.SneakyThrows;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author hl
 * @version 1.0.0
 * @ClassName FileController.java
 * @Description 类描述
 * @createTime 2023年05月05日 10:17:00
 */
@Controller
@RequestMapping("/api/File/")
public class FileController {



    @Autowired
    PlatStorageLogicService service;

    @Autowired
    PlatStorageService storageService;



    /***
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public R uploadFile(@RequestParam MultipartFile file,Integer id) throws IOException {
        String fileName=file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String relatePath=suffixName.replace(".","");
        PlatStorageLogic storageLogic =service.saveOrUpdateFile(file,id);
//        mate.setSourceName(fileName);
//        mate.setUrl(serverDomain+mate.getRalatePath());
        return  R.ok(storageLogic);
    }





//    @PostMapping("/create")
//    public Object create(@RequestParam("file") MultipartFile file) throws IOException {
//        String originalFilename = file.getOriginalFilename();
//        LitemallStorage litemallStorage = storageService.store(file.getInputStream(), file.getSize(),
//                file.getContentType(), originalFilename);
//        return ResponseUtil.ok(litemallStorage);
//    }



    @SneakyThrows
    @RequestMapping(value = "/preview")
    @ResponseBody
    public R downloadFile(HttpServletResponse response, String keyName,String id){
        PlatStorageLogic db=service.getByIdOrkeyName(keyName,id);
        if (Objects.isNull(db)){
            return R.error("文件不存在");
        }
        PlatStorage platStorage = storageService.getById(db.getStorageId());
        if (platStorage.getStorageType().equals("Local")){
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + URLEncoder.encode(platStorage.getFileKey(), "UTF-8"));
            InputStream input = new FileInputStream(platStorage.getFilePath());
            OutputStream out = response.getOutputStream();
            byte[] buff = new byte[1024];
            int index = 0;
            while ((index = input.read(buff)) != -1) {
                out.write(buff, 0, index);
                out.flush();
            }
            out.close();
            input.close();
            return R.ok();
        }
        response.sendRedirect(platStorage.getFileUrl());
        return  R.ok();


    }




    /***
     * 文件删除
     * @param
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/delete/{id}")
    public R removeFile( @PathVariable("id") Long id) throws IOException {
        return  R.ok(service.removeById(id) );
    }
}
